#include "stdafx.h"
#include "OpenCvWidget.h"

using namespace AirCrash::Calypso;

OpenCvWidget::OpenCvWidget(QWidget * parent) : QWidget(parent), mCameraStarted(false) {
	mCapture = cvCaptureFromCAM(1);
	if (!mCapture) {
		qDebug() << "Webcam not available";
	} else {
		qDebug() << "Webcam available";
		cvSetCaptureProperty(mCapture, CV_CAP_PROP_FRAME_WIDTH, Config::get("Settings", "width").toInt());
		cvSetCaptureProperty(mCapture, CV_CAP_PROP_FRAME_HEIGHT, Config::get("Settings", "height").toInt());
	}

	mRefreshTimer.setInterval(1000 / 24);
	connect( &mRefreshTimer, SIGNAL(timeout()), this, SLOT(nextFrame()) );
}

OpenCvWidget::~OpenCvWidget() {
	cvReleaseCapture(&mCapture);
}

void OpenCvWidget::showEvent(QShowEvent * e) {
	//if (mCameraStarted) {
		startCamera();
	//}
}

void OpenCvWidget::hideEvent(QHideEvent * e) {
	//bool tmpCamStarted(mCameraStarted);
	stopCamera();
	//mCameraStarted = tmpCamStarted;
}

void OpenCvWidget::startCamera() {
	mRefreshTimer.start();
	mCameraStarted = true;
}

void OpenCvWidget::stopCamera() {
	QWriteLocker lock(&mMutex);
	mRefreshTimer.stop();
	mCameraStarted = false;
	mCurrentFrame = QImage();
}

void OpenCvWidget::nextFrame() {
	{
		QWriteLocker lock(&mMutex);
		IplImage * frame = cvQueryFrame(mCapture);
		mCurrentFrame = IplToQImage(frame);
	}
	repaint();
}

QImage OpenCvWidget::getImage() {
	QReadLocker lock(&mMutex);
	return mCurrentFrame;
}

void OpenCvWidget::paintEvent(QPaintEvent * e) {
	QReadLocker lock(&mMutex);
	QPainter painter(this);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::HighQualityAntialiasing);

	if (!mCurrentFrame.isNull()) {
		int width(( mCurrentFrame.width() / float(mCurrentFrame.height()) ) * height());
		int xPos((this->width() - width) / 2);
		painter.drawImage(QRect(xPos, 0, width, height()), mCurrentFrame);
	} else {
		painter.fillRect(rect(), Qt::black);
	}
}